﻿namespace OpenLS.Spreadsheet
{
    class OfficeHash
    {
        static ushort getPasswordHash(string szPassword, int count)
        {
            ushort cchPassword = (ushort)count;
            ushort wPasswordHash = 0;
            if (cchPassword == 0)
                return wPasswordHash;
            for (int i = count - 1; i >= 0; i--)
            {
                // const char* pch = &szPassword[cchPassword];
                //  while (pch-- != szPassword)
                {
                    char pch = szPassword[i];
                    wPasswordHash = (ushort)(((wPasswordHash >> 14) & 0x01) |
                                             ((wPasswordHash << 1) & 0x7fff));
                    wPasswordHash ^= pch;
                }
            }

            wPasswordHash = (ushort)(((wPasswordHash >> 14) & 0x01) |
                                     ((wPasswordHash << 1) & 0x7fff));

            wPasswordHash ^= (0x8000 | ('N' << 8) | 'K');
            wPasswordHash ^= cchPassword;

            return wPasswordHash;
        }
        public static string GetPasswordHash(string s)
        {
            return getPasswordHash(s, s.Length).ToString("X");
        }
    }
}